package com.yuntsg.nnsfcp.service.front.ut;

import org.mindrot.jbcrypt.BCrypt;

import java.security.SecureRandom;
import java.util.regex.Pattern;

/**
 * 密码加密工具
 * 每次都生成不一样的密码, 但是他还可以解密. <N`B>
 *
 * @author ：ljx
 * @date ：Created in 2019/9/19
 */
public class BCryptPasswordEncoder {

    private final Pattern BCRYPT_PATTERN;
    private final SecureRandom random;
    private final Integer strength;


    public BCryptPasswordEncoder() {
        this(-1);
    }

    public BCryptPasswordEncoder(int strength) {
        this(strength, (SecureRandom) null);
    }

    public BCryptPasswordEncoder(int strength, SecureRandom random) {
        this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
        this.strength = strength;
        this.random = random;
    }

    /**
     * 加密
     *
     * @param rawPassword 用户输入密码
     * @return
     */
    public String encode(CharSequence rawPassword) {
        String salt;
        if (this.strength > 0) {
            if (this.random != null) {
                salt = BCrypt.gensalt(this.strength, this.random);
            } else {
                salt = BCrypt.gensalt(this.strength);
            }
        } else {
            salt = BCrypt.gensalt();
        }
        return BCrypt.hashpw(rawPassword.toString(), salt);
    }

    /**
     * 解密
     *
     * @param rawPassword     用户输入密码
     * @param encodedPassword 数据库密码
     * @return
     */
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword != null && encodedPassword.length() != 0) {
            if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
                return false;
            } else {
                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
            }
        } else {
            return false;
        }
    }


}
